"""
迁移人脸数据库，将图像文件复制到本地目录并更新路径
"""

import os
import sys
import shutil
import json

# 添加src目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from src.utils.data_storage import load_face_database, save_face_database
from src.modules.face_database import list_faces_in_database, get_face_image_path, add_face_to_database, remove_face_from_database
from src.modules.face_features import extract_face_features

def migrate_database():
    # 加载人脸数据库
    database_file = "data/face_database.json"
    face_database = load_face_database(database_file)
    
    print(f"人脸数据库中包含 {len(face_database)} 个人员:")
    
    # 创建本地图像存储目录
    local_images_dir = os.path.join("data", "face_images")
    if not os.path.exists(local_images_dir):
        os.makedirs(local_images_dir)
    
    migrated_count = 0
    failed_count = 0
    
    # 处理每个人脸数据
    for name in list(face_database.keys()):
        try:
            face_data = face_database[name]
            
            # 检查是否是旧格式（仅包含特征向量）
            if not isinstance(face_data, dict) or "image_path" not in face_data:
                print(f"  {name}: 旧格式数据，跳过迁移")
                continue
            
            # 获取原始图像路径
            original_image_path = face_data["image_path"]
            
            # 检查图像文件是否存在
            if not os.path.exists(original_image_path):
                print(f"  {name}: 原始图像文件不存在 ({original_image_path})")
                continue
            
            # 生成本地文件名
            import time
            timestamp = int(time.time() * 1000)  # 毫秒时间戳
            image_filename = f"{name}_{timestamp}{os.path.splitext(original_image_path)[1]}"
            local_image_path = os.path.join(local_images_dir, image_filename)
            
            # 复制图像文件到本地目录
            shutil.copy2(original_image_path, local_image_path)
            
            # 更新数据库中的图像路径
            face_database[name]["image_path"] = local_image_path
            
            print(f"  {name}: 迁移成功")
            migrated_count += 1
            
        except Exception as e:
            print(f"  {name}: 迁移失败 - {str(e)}")
            failed_count += 1
    
    # 保存更新后的数据库
    if save_face_database(face_database, database_file):
        print(f"\n数据库迁移完成: 成功 {migrated_count} 个, 失败 {failed_count} 个")
        print("数据库已保存到:", database_file)
    else:
        print(f"\n数据库保存失败!")

if __name__ == "__main__":
    migrate_database()